package multichatserver;

import java.net.*;
import java.io.*;
import java.util.ArrayList;

public class ChatServerHandler extends Thread {

    static final int ACCEPT = 0;
    static final int NICK = 1;
    static final int UNSIGN = 2;
    static final int MSG = 3;
    //String[] messages = {"accept", "param", "ping", "alive", "disconnect", "wait"};
    Client client;
    ArrayList<Client> clients;

    public ChatServerHandler(Client client, ArrayList<Client> clients) {
        this.client = client;
        this.clients = clients;
        System.out.println("Client connection from (" +
                client.addr + ", " + client.port + ")");
    } // end of ChatServerHandler()

    public void run() {
        try {
            String line;
            boolean done = false;
            
            while (!done) {
                System.out.println("waiting");
                if ((line = client.in.readLine()) == null) {
                    done = true;
                    break;
                }
                System.out.println(client.nick + ": " + line);
                int msgType = Integer.valueOf(line);
                switch (msgType) {
                    case UNSIGN:
                        done = true;
                        break;
                    case NICK:
                        client.nick = client.in.readLine();
                        System.out.println("nick :" + client.nick);
                        break;
                    case MSG:
                        // rozeslani zprav vsem klientum
                        line = client.in.readLine();
                        for (int i = 0; i < clients.size(); i++) {
                            System.out.println("sending nick: " + client.nick);
                            clients.get(i).sendMessage(client.id + "  " + client.nick + ": " + line);
                        }
                        break;
                    default:
                        break;
                }
            }// konec - prisla null zprava

            client.sock.close();
            System.out.println("Client (" + client.addr + ", " +
                    client.port + ") connection closed\n");
        } catch (Exception e) {
            System.out.println(e);
        }
    }  // end of run()
}
